<?php
header('Content-Type: application/json; charset=utf-8');

// 引入数据库配置
$dbConfig = include('db_config.php');

// 获取用户请求参数
$user_id = $_REQUEST['user_id'] ?? null;
$keyword = $_REQUEST['keyword'] ?? null;

// 参数验证
if (empty($user_id) || empty($keyword)) {
    echo json_encode(['status' => 'error', 'message' => '缺少必要的参数'], JSON_UNESCAPED_UNICODE);
    exit();
}

if (!is_numeric($user_id)) {
    echo json_encode(['status' => 'error', 'message' => '无效的用户 ID'], JSON_UNESCAPED_UNICODE);
    exit();
}

try {
    // 数据库连接
    $dsn = "mysql:host=" . $dbConfig['host'] . ";dbname=" . $dbConfig['dbname'] . ";charset=" . $dbConfig['charset'];
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 查询语句
    $sql = "
        SELECT * FROM mi_file 
        WHERE 上传者用户的id = :user_id 
        AND (文件标题 LIKE CONCAT('%', :keyword, '%') OR 文件介绍 LIKE CONCAT('%', :keyword, '%'))
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
    $stmt->bindParam(':keyword', $keyword, PDO::PARAM_STR);
    $stmt->execute();

    // 获取查询结果
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($result)) {
        echo json_encode(['status' => 'success', 'message' => '没有找到与关键词相关的文件'], JSON_UNESCAPED_UNICODE);
        exit();
    }

    echo json_encode(['status' => 'success','message' => '完成', 'data' => $result], JSON_UNESCAPED_UNICODE);

} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => '数据库查询失败：' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
    exit();
}
